package com.jakewharton.rxbinding2.component;

import com.jakewharton.rxbinding2.InitialValueObservable;
import io.reactivex.Observer;
import io.reactivex.ohos.MainThreadDisposable;
import ohos.agp.components.Component;
import ohos.agp.components.Component.FocusChangedListener;

final class ComponentFocusChangeObservable extends InitialValueObservable<Boolean> {
  private final Component view;

  ComponentFocusChangeObservable(Component view) {
    this.view = view;
  }

  @Override protected void subscribeListener(Observer<? super Boolean> observer) {
    Listener listener = new Listener(view, observer);
    observer.onSubscribe(listener);
    view.setFocusChangedListener(listener);
  }

  @Override protected Boolean getInitialValue() {
    return view.hasFocus();
  }

  static final class Listener extends MainThreadDisposable implements FocusChangedListener {
    private final Component view;
    private final Observer<? super Boolean> observer;

    Listener(Component view, Observer<? super Boolean> observer) {
      this.view = view;
      this.observer = observer;
    }

    @Override public void onFocusChange(Component v, boolean hasFocus) {
      if (!isDisposed()) {
        observer.onNext(hasFocus);
      }
    }

    @Override protected void onDispose() {
      view.setFocusChangedListener(null);
    }
  }
}
